package top.kaoshanji.p1ch04a;

import org.apache.commons.codec.binary.Hex;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单 p1ch04a-03：CharsetEncoder类的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/14 18:19
 */
public class CharsetEncoderExample01 {

    private static final Logger logger = LogManager.getLogger(CharsetEncoderExample01.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch04a-03：CharsetEncoder类的使用示例...");

        CharsetEncoderExample01 example = new CharsetEncoderExample01();
        example.simpleEncode();

    }

    public void simpleEncode() {
        Charset charset = StandardCharsets.UTF_8;
        CharsetEncoder encoder = charset.newEncoder();
        CharBuffer inputBuffer = CharBuffer.allocate(256);
        inputBuffer.put("你好").flip();

        ByteBuffer outBuffer = ByteBuffer.allocate(256);
        encoder.encode(inputBuffer, outBuffer, true);
        encoder.flush(outBuffer);

        outputBytes(outBuffer);
    }

    private void outputBytes(ByteBuffer buffer) {
        buffer.flip();
        byte[] data = new byte[buffer.limit()];
        buffer.get(data);
        System.out.println(Hex.encodeHex(data));
    }

}
